/*
 * Copyright (C) 2010-2011 Graz University of Technology, Austria. All Rights reserved. 
 *
 * Contact: Simone Kopeinik <simone.kopeinik@tugraz.at>
 * 	   Graz University of Technology, Knowledge Management Institute, Brückenkopfgasse 1/6, 8020 Graz 	
 * 	   <http://www.kmi.tugraz.at/>
 * 
 * This software is part of the TARGET platform developed by the
 * TARGET EC-funded project www.reachyourtarget.org
 *
 * This software is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * The GNU General Public License is available at <http://www.gnu.org/licenses/>.
 *
 */
package at.tugraz.kmi.css.cbkst2.prereq.structurevis;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import at.tugraz.kmi.css.cbkst2.CbKSTCompetence;
import at.tugraz.kmi.css.cbkst2.ImmutablePrerequesiteOrderSet;
import ca.odell.glazedlists.TreeList;

import com.google.common.collect.ImmutableSet;

final class PrerequesiteTreeListFormat implements
		TreeList.Format<CbKSTCompetence> {

	private ImmutablePrerequesiteOrderSet<CbKSTCompetence>	graph;

	/**
	 * @param jungPrerequesiteGraph
	 */
	public PrerequesiteTreeListFormat(
			ImmutablePrerequesiteOrderSet<CbKSTCompetence> jungPrerequesiteGraph) {
		graph = jungPrerequesiteGraph;
	}

	public void setGraph(
			ImmutablePrerequesiteOrderSet<CbKSTCompetence> jungPrerequesiteGraph) {
		graph = jungPrerequesiteGraph;
	}

	@Override
	public void getPath(List<CbKSTCompetence> path, CbKSTCompetence element) {
		path.add(element);
		CbKSTCompetence currentCompetence = element;
		addLayer(path, currentCompetence);
		Collections.reverse(path);
	}

	private void addLayer(List<CbKSTCompetence> path,
			CbKSTCompetence currentCompetence) {
		ImmutableSet<CbKSTCompetence> descendants = graph
				.getDescendants(currentCompetence);
		for (CbKSTCompetence cbKSTCompetence : descendants) {
			path.add(cbKSTCompetence);
			addLayer(path, cbKSTCompetence);
		}
	}

	@Override
	public boolean allowsChildren(CbKSTCompetence element) {
		return true;
	}

	@Override
	public Comparator<? extends CbKSTCompetence> getComparator(int depth) {
		return new Comparator<CbKSTCompetence>() {

			@Override
			public int compare(CbKSTCompetence o1, CbKSTCompetence o2) {

				String name = o1.getName();
				String name2 = o2.getName();

				if (name != null && name2 != null)
					return name.compareTo(name2);
				else
					return 0;
			}
		};

	}
}